//
//  RegisterViewController.m
//  AmazingShopping
//
//  Created by Tan on 5/13/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"Registration";
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [self.tableView addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTableView:nil];
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated{
    [self isTextFilled];
}

- (void)legalLabelClicked:(UITapGestureRecognizer *)sender{
    UILabel *label = (UILabel *)sender.view;
    NSLog(@"%@", label.text);
}

- (void)registerButtonClicked{
    if ([passwordTextField.text isEqualToString:confirmPasswordTextField.text]) {
        //Set effect
        self.view.userInteractionEnabled = NO;
        self.view.alpha = 0.5;
        UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:loading];
        [loading startAnimating];
        
        //Send data to server
        serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
        NSString *path = [NSString stringWithFormat:@"%@/register", serverPath];
        NSURL *url = [NSURL URLWithString:path];
        ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:url];
        [request addPostValue:fullNameTextField.text forKey:@"name"];
        [request addPostValue:emailTextField.text forKey:@"email"];
        [request addPostValue:passwordTextField.text forKey:@"password"];
        [request setDelegate:self];
        [request startSynchronous];
        
        //Stop effect
        [loading stopAnimating];
        self.view.userInteractionEnabled = YES;
        self.view.alpha = 1;
        
        //Processing response data
        NSError *error = [request error];
        if (!error) {
            NSData *responseData = [request responseData];
            JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
            NSArray *userInfo = [jsonDecoder objectWithData:responseData];
            NSLog(@"%@", userInfo);
            NSString *status = [userInfo valueForKey:@"status"];
            if ([status isEqualToString:@"SUCCESS"]) {
                isLogin = YES;
                NSString *userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
                NSMutableDictionary *userData = [[NSMutableDictionary alloc] initWithContentsOfFile: userInfoPath];
                [userData setObject:@"YES" forKey:@"IsLogin"];
                [userData setObject:emailTextField.text forKey:@"Email"];
                [userData setObject:fullNameTextField.text forKey:@"Name"];
                [userData setObject:[userInfo valueForKey:@"id"] forKey:@"ID"];
                [userData writeToFile:userInfoPath atomically:YES];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                NSLog(@"fail");
            }
        }else{
            NSLog(@"register error");
        }
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Password is not match" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alertView show];
    }
}

- (BOOL)isTextFilled{
    if ((emailTextField.text == nil) || [emailTextField.text isEqualToString:@""] || (passwordTextField.text == nil) || [passwordTextField.text isEqualToString:@""] || (confirmPasswordTextField.text == nil) || [confirmPasswordTextField.text isEqualToString:@""] || (fullNameTextField.text == nil) || [fullNameTextField.text isEqualToString:@""]) {
        registerButton.enabled = NO;
        return NO;
    }
    registerButton.enabled = YES;
    return YES;
}

- (void)hideKeyboard{
    [emailTextField resignFirstResponder];
    [fullNameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    [confirmPasswordTextField resignFirstResponder];
}


#pragma mark Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"Register below";
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = [indexPath row];
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RegisterCell"];
    CGRect frame = cell.frame;
    if ([indexPath section] == 0) {
        CGRect tempFrame = CGRectMake(frame.origin.x+15, frame.origin.y, frame.size.width-25, frame.size.height);
        switch (row) {
        case 0:{            
            fullNameTextField = [[UITextField alloc]initWithFrame:tempFrame];
            fullNameTextField.placeholder = @"Full name";
            fullNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
            fullNameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            fullNameTextField.autocorrectionType = UITextAutocorrectionTypeNo;
            [fullNameTextField addTarget:self action:@selector(isTextFilled) forControlEvents:UIControlEventEditingChanged];
            fullNameTextField.delegate = self;
            [cell addSubview:fullNameTextField];
        }
            break;
            
        case 1:{
            emailTextField = [[UITextField alloc]initWithFrame:tempFrame];
            emailTextField.placeholder = @"E-mail address";
            emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
            emailTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            emailTextField.autocorrectionType = UITextAutocorrectionTypeNo;
            [emailTextField addTarget:self action:@selector(isTextFilled) forControlEvents:UIControlEventEditingChanged];
            [emailTextField setKeyboardType:UIKeyboardTypeEmailAddress];
            emailTextField.delegate = self;
            [cell addSubview:emailTextField];
        }
            break;
            
        case 2:{
            passwordTextField = [[UITextField alloc]initWithFrame:tempFrame];
            passwordTextField.placeholder = @"Enter a password";
            passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
            passwordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            passwordTextField.autocorrectionType = UITextAutocorrectionTypeNo;
            [passwordTextField setSecureTextEntry:YES];
            [passwordTextField addTarget:self action:@selector(isTextFilled) forControlEvents:UIControlEventEditingChanged];
            passwordTextField.delegate = self;
            [cell addSubview:passwordTextField];
        }
            break;
            
        case 3:{
            confirmPasswordTextField = [[UITextField alloc]initWithFrame:tempFrame];
            confirmPasswordTextField.placeholder = @"Re-enter password";
            confirmPasswordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
            confirmPasswordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            confirmPasswordTextField.autocorrectionType = UITextAutocorrectionTypeNo;
            [confirmPasswordTextField addTarget:self action:@selector(isTextFilled) forControlEvents:UIControlEventEditingChanged];
            [confirmPasswordTextField setSecureTextEntry:YES];
            confirmPasswordTextField.delegate = self;
            [cell addSubview:confirmPasswordTextField];
        }
            break;
            
        default:
            break;
        }

    }else{
        switch (row) {
            case 0:{
                CGRect tempFrame = CGRectMake(frame.origin.x+8, frame.origin.y - 10, 100, frame.size.height - 10);
                registerButton = [[UIButton alloc]initWithFrame:tempFrame];
                [registerButton setTitle:@"Register" forState:UIControlStateNormal];
                [registerButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12.0f]];
                [registerButton setTitleColor:[UIColor colorWithRed:50/255.0 green:79/255.0 blue:123/255.0 alpha:1] forState:UIControlStateNormal];
                [registerButton setBackgroundImage:[UIImage imageNamed:@"button.png"]forState:UIControlStateNormal];
                [registerButton addTarget:self action:@selector(registerButtonClicked) forControlEvents:UIControlEventTouchUpInside];
                cell.backgroundView = [[UIView alloc]initWithFrame:CGRectZero];
                [cell addSubview:registerButton];
            }
                break;
                
            case 1:{
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x+10, frame.origin.y, frame.size.width-20, frame.size.height)];
                label.backgroundColor = [UIColor clearColor];
                label.text = @"By creating an account you agree to Our Conditions of Use and Privacy Policy";
                label.font = [UIFont fontWithName:@"Helvetica" size:12.0f];
                label.numberOfLines = 0;
                label.textColor = [UIColor colorWithRed:50/255.0 green:79/255.0 blue:123/255.0 alpha:1];
                [label sizeToFit];
                
                label.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(legalLabelClicked:)];
                [label addGestureRecognizer:tapGesture];
                [cell addSubview:label];
                cell.backgroundView = [[UIView alloc]initWithFrame:CGRectZero];
            }
                break;
                
            default:
                break;
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark Text Field Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == fullNameTextField) {
        [emailTextField becomeFirstResponder];
        return NO;
    }else if (textField == emailTextField){
        [passwordTextField becomeFirstResponder];
        return NO;
    }else if (textField == passwordTextField){
        [confirmPasswordTextField becomeFirstResponder];
        return NO;
    }else if ([self isTextFilled]){
        [self registerButtonClicked];
    }
    return YES;
}

@end
